<template>
  <div class="app-container">
    <el-form v-enterToNext="true" ref="postForm" :model="postForm" :rules="rules" label-position="left" label-width="110px" size="mini" status-icon >
      <el-form-item label="客户姓名" prop="Name">
        <el-select v-model="postForm.Name" filterable clearable placeholder="请选择" size="mini" @change="customerChange">
          <el-option
            v-for="item in customers"
            :key="item.ID"
            :label="item.Name"
            :value="item"/>
        </el-select>
      </el-form-item>
      <el-form-item label="客户电话" prop="Tel">
        <span>{{ postForm.Tel }}</span>
      </el-form-item>
      <el-form-item label="送货地址" prop="DeliveryAddress">
        <span>{{ postForm.DeliveryAddress }}</span>
      </el-form-item>
      <el-form-item label="送货时间" prop="DeliveryTime">
        <el-date-picker
          v-model="postForm.DeliveryTime"
          type="datetime"
          placeholder="选择日期时间"/>
      </el-form-item>
      <el-form-item v-if="1===2" label="订单总额" prop="Amount">
        <el-input v-model.number="postForm.Amount" type="number"/>
      </el-form-item>
      <el-form-item label="销售类型" prop="OrderTrade">
        <el-select v-model="postForm.OrderTrade" filterable clearable placeholder="请选择" size="mini">
          <el-option
            v-for="item in orderTrades"
            :key="item.ID"
            :label="item.Name"
            :value="item.ID"/>
        </el-select>
      </el-form-item>
      <el-form-item label="销售渠道" prop="OrderLine">
        <el-select v-model="postForm.OrderLine" filterable clearable placeholder="请选择" size="mini">
          <el-option
            v-for="item in orderLines"
            :key="item.ID"
            :label="item.Name"
            :value="item.ID"/>
        </el-select>
      </el-form-item>
      <el-form-item label="备注" prop="Remarks">
        <el-input v-model="postForm.Remarks"/>
      </el-form-item>

    </el-form>
    <br>
    <span style="font-size: 14px;font-weight: 700;color: red;font-family: Helvetica Neue, Helvetica, PingFang SC, Hiragino Sans GB, Microsoft YaHei, Arial, sans-serif;margin-left: 8px"> 请选择成品:</span>
    <el-select v-model="selectValue" filterable clearable placeholder="请选择" size="mini" @change="selectChange">
      <el-option
        v-for="item in options"
        :key="item.ID"
        :label="item.No"
        :value="item"
        :disabled="item.Disabled"/>
    </el-select>
    <el-table :data="commodities" style="width: 100%">
      <el-table-column label="编号" prop="No"/>
      <!--      <el-table-column label="类型" prop="Type"/>-->
      <el-table-column label="名称" prop="Name"/>
      <!--      <el-table-column label="成品库存" prop="Number"/>-->
      <el-table-column label="单个成品进价(元)" prop="PurchasePrice"/>
      <el-table-column label="供应商" prop="Supply"/>
      <el-table-column label="库存" prop="Number"/>
      <el-table-column label="单位" prop="Unit">
        <template slot-scope="scope">
          <el-select v-model="scope.row.Unit" filterable clearable placeholder="请选择" size="mini">
            <el-option
              v-for="item in units"
              :key="item.ID"
              :label="item.Name"
              :value="item.ID"/>
          </el-select>
        </template>
      </el-table-column>

      <el-table-column label="数量" width="150">
        <template slot-scope="scope">
          <el-input-number v-model="scope.row.Quantity" :min="0" size="mini"/>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="mini" type="danger" icon="el-icon-delete" circle @click="handleDelete(scope.$index,scope.row)"/>
        </template>
      </el-table-column>
    </el-table>
    <br >
    <div>
      <el-button :loading="loading" type="primary" size="mini" @click="submitForm">提交</el-button>
      <el-button size="mini" @click="resetForm">重置</el-button>
    </div>
  </div>
</template>

<script>

import { getCommoditiesStock } from '@/api/commodity'
import { createCustormerOrder } from '@/api/order'
import { getCustomer } from '@/api/customer'
// import { validateTel } from '@/utils/validate'

export default {
  data() {
    // const checkTel = (rule, value, callback) => {
    //   if (!validateTel(value)) {
    //     callback(new Error('必须是11位合法手机号'))
    //   } else {
    //     callback()
    //   }
    // }
    return {
      loading: false,
      selectValue: '',
      options: [],
      customers: [],
      orderTrades: [
        { ID: '内贸', Name: '内贸' },
        { ID: '外贸', Name: '外贸' }
      ],
      orderLines: [
        { ID: '线上', Name: '线上' },
        { ID: '线下', Name: '线下' }
      ],
      units: [
        { ID: '个', Name: '个' },
        { ID: '箱', Name: '箱' }
      ],
      commodities: [],
      postForm: {
        Name: '',
        Tel: '',
        DeliveryAddress: '',
        OrderTrade: '',
        OrderLine: '线下',
        DeliveryTime: '',
        Amount: null,
        Remarks: '',
        Goods: []
      },
      rules: {
        Name: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        Tel: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        DeliveryAddress: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        DeliveryTime: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        Remarks: [
          { max: 255, message: '最多255  个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      getCommoditiesStock().then(response => {
        console.log(response)
        this.options = response.map(item => {
          return {
            Quantity: 0,
            Unit: '个',
            ID: item.ID,
            No: item.No,
            Type: item.Type,
            Name: item.Name,
            Number: item.Number,
            PurchasePrice: item.PurchasePrice,
            Supply: item.Supply,
            Number: item.Number
          }
        })
      })
      getCustomer().then(response => {
        console.log(response)
        this.customers = response.map(item => {
          return {
            ID: item.Name,
            Name: item.Name,
            Tel: item.Tel,
            Address: item.Address,
            EmailAddress: item.EmailAddress,
            Manager: item.Manager
          }
        })
      })
    },
    submitForm() {
      this.$refs['postForm'].validate(valid => {
        if (valid) {
          const len = this.commodities.length
          if (len <= 0) {
            this.$message.error('请添加商品')
            return
          }
          for (let i = 0; i < len; i++) {
            if (this.commodities[i].Quantity <= 0) {
              this.$message.error('成品数量不能为 0')
              this.postForm.Goods = []
              return
            }
            // if (this.commodities[i].Quantity > this.commodities[i].Number) {
            //   this.$message.error('库存不足')
            //   this.postForm.Goods = []
            //   return
            // }
            this.postForm.Goods.push({
              ID: this.commodities[i].ID,
              Number: this.commodities[i].Quantity,
              Unit: this.commodities[i].Unit

            })
          }
          // this.postForm.Name = this.postForm.Name.Name
          console.log(this.postForm)
          this.loading = true
          createCustormerOrder(this.postForm)
            .then(response => {
              console.log(response)
              this.loading = false
              this.resetForm()
              this.$message.success('创建成功')
            })
            .catch((error) => {
              this.loading = false
              this.postForm.Goods = []
              if (error && error.response && error.response.data && error.response.data.error) {
                this.$message.error(error.response.data.error)
              } else {
                this.$message.error('创建失败')
              }
            })
        }
      })
    },
    selectChange() {
      if (this.selectValue !== '') {
        this.selectValue.Disabled = true
        this.commodities.push(this.selectValue)
        this.selectValue = ''
      }
    },
    handleDelete(index, row) {
      this.commodities.splice(index, 1)
      row.Disabled = false
    },
    resetForm() {
      this.postForm.Name = ''
      this.postForm.Tel = ''
      this.postForm.DeliveryAddress = ''
      this.postForm.OrderTrade = ''
      this.postForm.OrderLine = '线下'
      this.postForm.Unit = '个'
      this.postForm.DeliveryTime = ''
      this.postForm.Amount = null
      this.postForm.Remarks = ''
      this.postForm.Goods = []
      for (let i = 0; i < this.commodities.length; i++) {
        this.commodities[i].Disabled = false
      }

      this.commodities = []
    },
    customerChange(item) {
      this.postForm.Name = item.Name
      this.postForm.Tel = item.Tel
      this.postForm.DeliveryAddress = item.EmailAddress
    }
  }
}
</script>
<style scoped>

</style>
